package com.shhic.hhplt.server.service.impl;

import com.shhic.hhplt.server.mapper.ITestDbManageTestDao;
import com.shhic.hhplt.server.mapper.ITestDbManagerSysDao;
import com.shhic.hhplt.server.service.ITestDbManageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.util.*;

@Service
@Slf4j
public class TestDbManageServiceImpl implements ITestDbManageService {
    @Autowired
    private ITestDbManageTestDao testDao;
    @Autowired
    private ITestDbManagerSysDao sysDao;

    @Override
    public void execSql(String sql) {
        String[] sqlItems = sql.split(";");
        for(String sqlItem:sqlItems){
            testDao.execSql(sqlItem);
        }
    }

    @Override
    public int getTableCount() {
        return testDao.getTableCount();
    }

    /**
     * 数据库连接保持线程
     * 相当于一个周期（一个小时）的ping，以保持与数据库的长连接
     */
    @PostConstruct
    public void startDbConnectionMantaince(){
        log.info("数据库连接保持维护线程启动");
        new Timer().scheduleAtFixedRate(new TimerTask() {
            private String PING_CMD = "select 1";
            @Override
            public void run() {
                try{
                    testDao.execSql(PING_CMD);
                    sysDao.execSql(PING_CMD);
                    log.info("数据库连接保持Ping");
                }catch(Exception e){
                    log.error(null,e);
                }
            }
        },new Date(),1*3600*1000);
    }


}
